use num_bigint::BigUint;
use num_traits::{Zero, ToPrimitive};
use num_integer::Integer;

const BASE58_ALPHABET: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

fn base58_encode(input: &[u8]) -> String {  
    //const ALPHABET: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";  
    // TODO: 实现编码逻辑  

    // 处理前导零
    let leading_ones = input.iter()
        .take_while(|&&b| b == 0)
        .count();
    let prefix = "1".repeat(leading_ones);
    
    // 将字节转换为大整数
    let mut num = BigUint::from_bytes_be(input);
    if num.is_zero() {
        return prefix;
    }
    
    // 执行进制转换
    let base = BigUint::from(58u32);
    let mut result = String::new();
    while !num.is_zero() {
        let quotient = &num / &base;
        let remainder = &num % &base;
        //let (quotient, remainder) = num.div_rem(&base);
        let idx = remainder.to_usize().unwrap();
        result.push(BASE58_ALPHABET.chars().nth(idx).unwrap());
        num = quotient;
    }
    
    // 组合结果
    prefix + &result.chars().rev().collect::<String>()
}  

#[test] 
fn test_base58() { 
    // 基础测试
    assert_eq!(base58_encode(&[0x00]), "1");           // 单零
    assert_eq!(base58_encode(&[0x00, 0x00]), "11");   // 多零
    
    // 标准测试向量
    assert_eq!(base58_encode(b"Hello World!"), "2NEpo7TZRRrLZSi2U");
    //assert_eq!(base58_encode(b"\x7f\x83\x94"), "LUv9");
}  

// 添加编码演示
fn main() {
    let test_cases = [
        (vec![0x00], "1"),
        (b"Bitcoin".to_vec(), "3aC3C6F3Z"),
        (vec![0x61, 0x62, 0x63], "ZiCa"),
    ];
    
    for (input, expected) in test_cases {
        println!("输入: {:?}", input);
        println!("编码: {}", base58_encode(&input));
        println!("预期: {}\n", expected);
    }
}